package orz.mikeneck.server.locrec;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orz.mikeneck.server.locrec.controller.ApiHandler;
import orz.mikeneck.server.locrec.controller.ApiHandlerMatcher;
import orz.mikeneck.server.locrec.exception.ApiNotSupportedException;
import orz.mikeneck.server.locrec.model.LocRecGpsModel;
import orz.mikeneck.server.locrec.model.LocRecGpsModelImpl;
import orz.mikeneck.server.locrec.persistent.utils.PersistenceManagerUtil;

public class ApiServlet extends HttpServlet {

	private static final String LOGIN_ID = "loginId";

	private static final String MODE = "mode";

	private static final long serialVersionUID = 8772766992694273604L;

	private static final Logger log = Logger.getLogger(ApiServlet.class.getName());

	private static String MODE_NEW = "new";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String mode = getMode(req);
		try {
			ApiHandler handler = ApiHandlerMatcher.getHandler(mode);
			boolean result = handler.requestIs(req)
				.responseIs(resp)
				.execute();
			if(result){
				return;
			}else{
				resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);	
			}
		} catch (ApiNotSupportedException e) {
			resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	public String getMode(HttpServletRequest req){
		String mode = MODE_NEW;
		String param = req.getParameter(MODE);
		if(param != null){
			mode = param;
		}
		return mode;
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			ApiHandler handler = ApiHandlerMatcher.getHandler(ApiHandler.GetParams.MODE_GET);
			boolean result = handler
				.requestIs(req)
				.responseIs(resp)
				.execute();
			if(result){
				resp.setStatus(HttpServletResponse.SC_OK);
			}else{
				resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			}
		} catch (ApiNotSupportedException e) {
			resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
	}
}
